package cn.tedu.v6;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;



public class Client {
    private static final int MAX_ATTEMPTS = 3;
    private static final String HOST="127.0.0.1";
    private static final Integer PORT=3333;
    private Socket socket;

    private BufferedReader br;
    private PrintWriter pw;
    private String ip;
    public Client(){

        try {
            socket=new  Socket(HOST,PORT);
            ip=socket.getInetAddress().getHostAddress();
            br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
            pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);
        } catch (SocketException e) {
            System.out.println("连接被重置或者断开");
        } catch (UnknownHostException e) {
            System.out.println("IP地址有问题，请询问服务器端");
        }catch (IOException e) {
            System.out.println("客户端主动退出了");
        }

    }

    public void start() {

        try {

            new Thread(() -> {
                try {

                    String message;
                    while ((message = br.readLine()) != null) {
                        System.out.println(ip + "服务器端说：" + message/*br.readLine()*/);
                    }
                } catch (IOException e) {
                    System.out.println("服务器端断开了");
                }
            }).start();
            System.out.println(ip + "客户端：请输入文字：");
            Scanner input = new Scanner(System.in);
            while (true) {
                String say = input.nextLine();
                pw.println("客户端说" + say);
                System.out.println("发送");
                System.out.println("客户端请输入： ");
            }
        }  finally {
            if (br != null)
                try {
                    br.close();
                } catch (IOException e) {
                    System.out.println("客户端离开");
                }
                    if (pw != null)
                        pw.close();
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println("客户端离开");
                    }
                    if (socket != null && !socket.isClosed()) {
                        System.out.println(ip + "客户端关闭成功");
                        try {
                            socket.close();
                        } catch (IOException e) {
                            System.out.println(ip + "客户端关闭失败");
                        }
                    }
                }
        }
    public static void main(String[] args) {
        new Client().start();

    }
}